CODE 54. Word Search

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/10/01/2013-10-01-CODE 54 Word Search/

访问原文「CODE 54. Word Search

Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Givenboard=
[
[“ABCE”],
[“SFCS”],
[“ADEE”]
]

word = "ABCCED", -> returnstrue,
word = "SEE", -> returnstrue,
word = "ABCB", -> returnsfalse.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public boolean exist(char[][] board, String word) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == board || board.length <= 0) {
return false;
}
if (null == word || "".equals(word)) {
return true;
}
int rows = board.length;
int cols = board[0].length;
boolean[][] walked = new boolean[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (checkExist(board, word, i, j, 0, walked)) {
return true;
}
}
}
return false;
}
boolean checkExist(char[][] board, String word, int i, int j, int index,
boolean[][] walked) {
boolean existed = false;
if (board[i][j] == word.charAt(index) && !walked[i][j]) {
if (index == word.length() - 1) {
return true;
}
for (int m = -1; m <= 1; m++) {
for (int n = -1; n <= 1; n++) {
if (Math.abs(n - m) != 1 || i + m < 0
|| i + m >= board.length || j + n < 0
|| j + n >= board[0].length || walked[m + i][n + j]) {
continue;
}
walked[i][j] = true;
existed = checkExist(board, word, m + i, n + j, index + 1,
walked);
walked[i][j] = false;
if (existed) {
return existed;
}
}
}
}
return existed;
}
Jerky Lu wechat
欢迎加入微信公众号